import PocketBase from "../pocketbase.es.js";
const pb = new PocketBase("http://127.0.0.1:8090");

/* 事件委托（代理） */
export function _on(type, methods, ac = "action") {
  document.addEventListener(type, async (e) => {
    const action = e.target.dataset[ac];
    if (action === undefined) return;
    if (methods[action] === undefined) return;
    methods[action].call(e.target);
  });
}

export function renderTable(data = []) {
  const html = String.raw;
  return html` <table class="table table-striped">
    <thead>
      <tr>
        <th>姓名</th>
        <th>邮箱</th>
        <th>婚姻</th>
        <th>存款</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      ${data
        .map(
          (el) => html` <tr>
            <td>${el.name}</td>
            <td>${el.email}</td>
            <td>${el.marry ? "已婚" : "未婚"}</td>
            <td>${el.money}</td>
            <td>
              <button
                class="btn btn-info btn-sm"
                data-action="edit"
                data-edit-id="${el.id}"
              >
                <i class="fa-regular fa-pen-to-square"></i>
                编辑
              </button>
              <button
                class="btn btn-danger btn-sm"
                data-action="delete"
                data-delete-id="${el.id}"
              >
                <i class="fa-regular fa-trash-can"></i>
                删除
              </button>
            </td>
          </tr>`
        )
        .join("")}
    </tbody>
  </table>`;
}

export async function getLists() {
  try {
    const data = await pb.collection("employ").getFullList();
    document.getElementById("box").innerHTML = renderTable(data);
  } catch (error) {}
}
